package com.aisile.fastdfs.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Auther:yry
 * @Date:2024/1/5 0005
 * @VERSON:1.0
 */
@Component
public class OSSClientUtils {

    String accessKey = "LTAI5tCDV5mGiEsKesvfs9zf";
    String secretKey = "ggA56OT8SiTBkvKFkZdmGgx5gIyg0L";
    String host = "https://y2307a.oss-cn-beijing.aliyuncs.com/";
    String bucket = "y2307a";

    public String upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        //                         oss-cn-beijing.aliyuncs.com
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = bucket;
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String fileName = "";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 生成文件名
        fileName = file.getOriginalFilename();
        String fileFix = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileFix;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream());
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            return host + fileName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

}
